package mx.netbrain.dao.impl;

import java.util.List;

import mx.netbrain.dao.OrganizationDao;
import mx.netbrain.model.Organization;
import mx.netbrain.util.HibernateUtil;

import org.apache.log4j.Logger;
import org.hibernate.Session;

public class OrganizationDaoImpl implements OrganizationDao {

	private static final Logger logger = Logger
			.getLogger(OrganizationDaoImpl.class);

	@Override
	public void save(Organization organization) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.persist(organization);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Save: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public void delete(Organization organization) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.merge(organization);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Delete: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public void update(Organization organization) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.merge(organization);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Update: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public Organization findById(Long id) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		return (Organization) session.load(Organization.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Organization> listAll() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		return session
				.createQuery(
						"from Organization as organization where organization.status.id = 1")
				.list();
	}

}
